package org.spider.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.spider.model.dto.SpiderUser;
import org.spider.model.entity.SpiderAuthResourceEntity;
import org.spider.mapper.SpiderAuthResourceMapper;
import org.spider.model.entity.SpiderAuthUserRoleEntity;
import org.spider.service.SpiderAuthResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.spider.service.SpiderAuthUserRoleService;
import org.spider.system.dto.MenuDTO;
import org.spider.system.entity.Menu;
import org.spider.system.entity.Post;
import org.spider.system.entity.RoleMenu;
import org.spider.system.entity.RoleScope;
import org.spider.system.service.IRoleMenuService;
import org.spider.system.service.IRoleScopeService;
import org.spider.system.vo.MenuVO;
import org.spider.model.vo.SpiderAuthResourceVO;
import org.spider.system.wrapper.MenuWrapper;
import org.spider.system.wrapper.SpiderAuthResourceWrapper;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.node.ForestNodeMerger;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzy
 * @since 2022-06-18 22:40:07
 */
@Service
@AllArgsConstructor
public class SpiderAuthResourceServiceImp extends ServiceImpl<SpiderAuthResourceMapper, SpiderAuthResourceEntity> implements SpiderAuthResourceService {
    private final IRoleMenuService roleMenuService;
    private final IRoleScopeService roleScopeService;

    SpiderAuthUserRoleService spiderAuthUserRoleService;
    private final static String PARENT_ID = "parentId";

    @Override
    public IPage<MenuVO> selectMenuPage(IPage<MenuVO> page, MenuVO menu) {
        return page.setRecords(baseMapper.selectMenuPage(page, menu));
    }

    @Override
    public List<MenuVO> lazyMenuList(Long parentId, Map<String, Object> param) {
        if (Func.isEmpty(Func.toStr(param.get(PARENT_ID)))) {
            parentId = null;
        }
        return baseMapper.lazyMenuList(parentId, param);
    }

    @Override
    public List<SpiderAuthResourceVO> routes(Long userId) {
        if (ObjectUtils.isEmpty(userId)) {
            return null;
        }
        List<SpiderAuthResourceEntity> allResources = baseMapper.allResource();
        List<SpiderAuthUserRoleEntity> spiderAuthUserRoleEntities = spiderAuthUserRoleService
                .list(Wrappers.<SpiderAuthUserRoleEntity>query()
                        .lambda().eq(SpiderAuthUserRoleEntity::getUserId, userId));
        List<Long> roleIdList = new ArrayList<>();
        for (SpiderAuthUserRoleEntity spiderAuthUserRoleEntity : spiderAuthUserRoleEntities) {
            roleIdList.add(spiderAuthUserRoleEntity.getRoleId());
        }
        List<SpiderAuthResourceEntity> roleResources = baseMapper.roleResource(roleIdList);
        List<SpiderAuthResourceEntity> routes = new LinkedList<>(roleResources);
        roleResources.forEach(roleResource -> recursion(allResources, routes, roleResource));
        routes.sort(Comparator.comparing(SpiderAuthResourceEntity::getResourceOrder));
        SpiderAuthResourceWrapper menuWrapper = new SpiderAuthResourceWrapper();
        List<SpiderAuthResourceEntity> collect = routes.stream().filter(x -> Func.equals(x.getResourceType(), 1)).collect(Collectors.toList());
        return menuWrapper.listNodeVO(collect);
    }

    public void recursion(List<SpiderAuthResourceEntity> allResources, List<SpiderAuthResourceEntity> routes, SpiderAuthResourceEntity roleResources) {
        Optional<SpiderAuthResourceEntity> menu = allResources.stream().filter(x -> ObjectUtils.nullSafeEquals(x.getId(), roleResources.getResourceParentId())).findFirst();
        if (menu.isPresent() && !routes.contains(menu.get())) {
            routes.add(menu.get());
            recursion(allResources, routes, menu.get());
        }
    }

    @Override
    public List<SpiderAuthResourceVO> buttons(String roleId) {
        List<SpiderAuthResourceEntity> buttons = baseMapper.buttons(Func.toLongList(roleId));
        SpiderAuthResourceWrapper spiderAuthResourceWrapper = new SpiderAuthResourceWrapper();
        return spiderAuthResourceWrapper.listNodeVO(buttons);
    }

    @Override
    public List<MenuVO> tree() {
        return ForestNodeMerger.merge(baseMapper.tree());
    }

    @Override
    public List<MenuVO> grantTree(SpiderUser user) {
        return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantTree() : baseMapper.grantTreeByRole(Func.toLongList(user.getRoleId())));
    }

    @Override
    public List<MenuVO> grantDataScopeTree(SpiderUser user) {
        return ForestNodeMerger.merge(user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) ? baseMapper.grantDataScopeTree() : baseMapper.grantDataScopeTreeByRole(Func.toLongList(user.getRoleId())));
    }

    @Override
    public List<String> roleTreeKeys(String roleIds) {
        List<RoleMenu> roleMenus = roleMenuService.list(Wrappers.<RoleMenu>query().lambda().in(RoleMenu::getRoleId, Func.toLongList(roleIds)));
        return roleMenus.stream().map(roleMenu -> Func.toStr(roleMenu.getMenuId())).collect(Collectors.toList());
    }

    @Override
    public List<String> dataScopeTreeKeys(String roleIds) {
        List<RoleScope> roleScopes = roleScopeService.list(Wrappers.<RoleScope>query().lambda().in(RoleScope::getRoleId, Func.toLongList(roleIds)));
        return roleScopes.stream().map(roleScope -> Func.toStr(roleScope.getScopeId())).collect(Collectors.toList());
    }

    @Override
    public List<Kv> authRoutes(SpiderUser user) {
        if (Func.isEmpty(user)) {
            return null;
        }
        List<MenuDTO> routes = baseMapper.authRoutes(Func.toLongList(user.getRoleId()));
        List<Kv> list = new ArrayList<>();
        routes.forEach(route -> list.add(Kv.init().set(route.getPath(), Kv.init().set("authority", Func.toStrArray(route.getAlias())))));
        return list;
    }

}
